package com.wocai.jrt.orgadmin.riskEvaluation.action;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.wocai.jrt.orgadmin.investor.bean.InvestorResBean;
import com.wocai.jrt.orgadmin.investor.model.Investor;
import com.wocai.jrt.orgadmin.investor.service.spi.InvestorService;
import com.wocai.jrt.orgadmin.riskEvaluation.bean.QuestionDetailBean;
import com.wocai.jrt.orgadmin.riskEvaluation.bean.QuestionReqBean;
import com.wocai.jrt.orgadmin.riskEvaluation.model.Options;
import com.wocai.jrt.orgadmin.riskEvaluation.model.Paper;
import com.wocai.jrt.orgadmin.riskEvaluation.model.Question;
import com.wocai.jrt.orgadmin.riskEvaluation.service.spi.AnswerService;
import com.wocai.jrt.orgadmin.riskEvaluation.service.spi.OptionsService;
import com.wocai.jrt.orgadmin.riskEvaluation.service.spi.PaperService;
import com.wocai.jrt.orgadmin.riskEvaluation.service.spi.QuestionService;
import com.wocai.jrt.orgadmin.utils.MyFileUtils;
import com.wocai.jrt.orgadmin.utils.UserUtils;
import com.lowagie.text.pdf.BaseFont;
import com.vteba.utils.common.PropsUtils;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;

/**
 * 题库题目控制器
 * 
 * @author zhangyz
 * @date 2015-10-28 16:03:03
 */
@Controller
@RequestMapping("/question")
public class QuestionAction extends GenericAction<Question> {
	private static final Logger LOGGER = LoggerFactory.getLogger(QuestionAction.class);

	@Inject
	private QuestionService questionServiceImpl;
	@Inject
	private OptionsService optionsServiceImpl;
	@Inject
	private PaperService paperServiceImpl;
	@Inject
	private AnswerService answerServiceImpl;
	@Inject
	private InvestorService investorServiceImpl;
	
	/**
	 * 获得投资人List，初始化列表页。
	 * 
	 * @param model
	 *            参数
	 * @return 投资人List
	 */
	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(@RequestBody Investor model) {

		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Date date = model.getEndTime();
			if (date != null) {
				model.setEndTime(new DateTime(date).plusHours(23).plusMinutes(59).plusSeconds(59)
						.toDate());
			}
			// 获取当前机构ID
			model.setOrgId(UserUtils.getOrgId());
			String groups = model.getEmpGroup();
			if (groups != null && !groups.equals("")) {
				List<String> groupList = new ArrayList<String>();
				String[] str = groups.split(",");
				for (String string : str) {
					groupList.add(string);
				}
				model.setEmpGroupList(groupList);
			}
			model.setOrderBy("register_time desc");
			List<InvestorResBean> list = investorServiceImpl.queryMyList(model);
			// 统计的时候，不需要分页
			model.setPage(null);
			long totalRecord = investorServiceImpl.queryMyList(model).size();

			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("Investor query success.");
			}
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("Investor query error, msg=[{}]", e.getMessage());
		}
		return result;
	}
	
	/**
	 * 获得题库题目List(分页)。
	 * 
	 * @param model
	 *            参数
	 * @return 题库题目List
	 */
	@ResponseBody
	@RequestMapping("/list")
	public Map<String, Object> list(@RequestBody Question model) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			model.setOrgId(UserUtils.getOrgId());
			model.setOrderBy("create_time desc");
			//model.setStart(model.getPage());
			model.setTag(true);
			List<Question> list = questionServiceImpl.queryMyList(model);
			// 统计的时候，不需要分页
			model.setPage(null);
			long totalRecord = questionServiceImpl.queryMyList(model).size();

			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("quaetion query success.");
			}
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("get quaetion list error, errorMsg=[{}].", e.getMessage());
		}
		return result;
	}
	
	/**
	 * 获得题库题目List (不分页)。
	 * 
	 * @param model
	 *            参数
	 * @return 题库题目List
	 */
	@ResponseBody
	@RequestMapping("/mylist")
	public Map<String, Object> mylist( Question model) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			model.setOrgId(UserUtils.getOrgId());
			model.setOrderBy("create_time desc");
			model.setTag(true);
			List<Question> list = questionServiceImpl.queryList(model);
			// 统计的时候，不需要分页
			model.setPage(null);
			long totalRecord = questionServiceImpl.queryList(model).size();

			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("quaetion query success.");
			}
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("get quaetion list error, errorMsg=[{}].", e.getMessage());
		}
		return result;
	}
	
	/**
	 * 根据Id获得题库题目实体，Json格式。
	 * 
	 * @param id
	 *            参数id
	 * @return 题库题目实体
	 */
	@ResponseBody
	@RequestMapping("/get")
	public Question get(String id) {
		Question model = null;
		try {
			model = questionServiceImpl.get(id);
		} catch (Exception e) {
			LOGGER.error("get record error, errorMsg=[{}].", e.getMessage());
		}
		return model;
	}

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 * @return 新增页面逻辑视图
	 */
	@ResponseBody
	@RequestMapping("/doAdd")
	public JsonBean doAdd(@RequestBody QuestionReqBean model) {
		JsonBean bean = new JsonBean();
		try {
			// 构建选项
			String questionId = ObjectId.get().toString();
			String[] optionStrs = model.getOptions().split(",");
			List<Options> optionList = new ArrayList<Options>();
			StringBuilder unqualifiedSrt = new StringBuilder();
			for (int i = 0; i < (int) optionStrs.length / 4; i++) {
				Options opt = new Options();
				opt.setId(ObjectId.get().toString());
				opt.setQuestionId(questionId);
				opt.setNo(optionStrs[i * 4]);
				opt.setContent(optionStrs[i * 4 + 1]);
				opt.setScore(Integer.parseInt(optionStrs[i * 4 + 2]));
				if ("是".equals(optionStrs[i * 4 + 3])) {
					opt.setUnqualified(true);
					unqualifiedSrt.append(optionStrs[i * 4]);
				} else {
					opt.setUnqualified(false);
				}
				optionList.add(opt);
			}
			// 构建试题
			Question question = new Question();
			question.setId(questionId);
			question.setTitle(model.getQuestion());
			if (model.getIsMulti() == 1) {
				question.setOptions(true);
			} else {
				question.setOptions(false);
			}
			question.setUnqualified(unqualifiedSrt.toString().replace(" ", ""));
			question.setOrgId(UserUtils.getOrgId());
			question.setCreateTime(new Date());
			question.setTag(true);
			int result = questionServiceImpl.save(question);
			int result_opts = optionsServiceImpl.insertBatch(optionList);
			if (result == 1 && result_opts == optionList.size()) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("save question and options record success.");
			} else {
				bean.setMessage(ERROR);
				bean.setCode(0);
				LOGGER.error("save question and options record error.");
			}
		} catch (Exception e) {
			bean.setCode(0);
			LOGGER.error("save question and options record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 查看题库题目详情页。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 题库题目详情页
	 */
	@ResponseBody
	@RequestMapping("/detail")
	public JsonBean detail(@RequestBody Question model, Map<String, Object> maps) {
		JsonBean bean = new JsonBean();
		try {
			// 获取试题
			Question question = questionServiceImpl.get(model.getId());
			// 获取该试题所有选项
			Options options = new Options();
			options.setQuestionId(model.getId());
			options.setOrderBy("no asc");
			List<Options> optList = optionsServiceImpl.pagedList(options);
			maps.put("question", question);
			maps.put("optList", optList);
			bean.setData(maps);
			bean.setCode(1);
		} catch (Exception e) {
			bean.setCode(0);
			LOGGER.error("query question detail, errorMsg=[{}].", e.getMessage());
		}
		return bean;
	}

	/**
	 * 跳转到编辑信息页面
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 编辑页面
	 */
	@RequestMapping("/edit")
	public String edit(Question model, Map<String, Object> maps) {
		model = questionServiceImpl.get(model.getId());
		maps.put("model", model);
		return "question/edit";
	}

	/**
	 * 修改题库题目信息
	 * 
	 * @param model
	 *            要更新的题库题目信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/modify")
	public JsonBean update(@RequestBody QuestionReqBean model) {
		JsonBean bean = new JsonBean();
		try {
			// 构建选项
			String questionId = model.getQuestionId();
			String[] optionStrs = model.getOptions().split(",");
			List<Options> optionList = new ArrayList<Options>();
			StringBuilder unqualifiedSrt = new StringBuilder();
			for (int i = 0; i < (int) optionStrs.length / 4; i++) {
				Options opt = new Options();
				opt.setId(ObjectId.get().toString());
				opt.setQuestionId(questionId);
				opt.setNo(optionStrs[i * 4]);
				opt.setContent(optionStrs[i * 4 + 1]);
				opt.setScore(Integer.parseInt(optionStrs[i * 4 + 2]));
				if ("是".equals(optionStrs[i * 4 + 3])) {
					opt.setUnqualified(true);
					unqualifiedSrt.append(optionStrs[i * 4]);
				} else {
					opt.setUnqualified(false);
				}
				optionList.add(opt);
			}
			// 构建试题
			Question question = new Question();
			question.setId(questionId);
			question.setTitle(model.getQuestion());
			question.setUpdateTime(new Date());
			if (model.getIsMulti() == 1) {
				question.setOptions(true);
			} else {
				question.setOptions(false);
			}
			question.setUnqualified(unqualifiedSrt.toString().replace(" ", ""));
			question.setTag(true);
			// 修改试题
			int result = questionServiceImpl.updateById(question);
			// 批量删除试题选项
			Options delOpts = new Options();
			delOpts.setQuestionId(questionId);
			optionsServiceImpl.deleteBulks(delOpts);
			// 批量新增试题选项
			int result_opts = optionsServiceImpl.insertBatch(optionList);
			if (result == 1 && result_opts == optionList.size()) {
				bean.setMessage("修改试题成功!");
				bean.setCode(1);
				LOGGER.info("modify question and options success.");
			} else {
				bean.setCode(0);
				bean.setMessage("修改试题失败!");
				LOGGER.error("modify question and options error.");
			}
		} catch (Exception e) {
			bean.setCode(0);
			LOGGER.error("modify question and options error, errorMsg=[{}].", e.getMessage());
			bean.setMessage("修改试题失败!");
		}
		return bean;
	}

	/**
	 * 删除题库题目信息
	 * 
	 * @param id
	 *            要删除的题库题目ID
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public JsonBean delete(@RequestBody Question model) {
		JsonBean bean = new JsonBean();
		if (model.getId() == null) {
			bean.setMessage("参数异常!");
			bean.setCode(0);
			return bean;
		}
		String questionId = model.getId();
		try {
			// 删除试题
			int result = questionServiceImpl.deleteById(questionId);
			// 删除试题选项
			Options opts = new Options();
			opts.setQuestionId(questionId);
			int result_opt = optionsServiceImpl.deleteBulks(opts);
			if (result == 1 && result_opt >= 1) {
				bean.setMessage("试题删除成功!");
				bean.setCode(1);
				LOGGER.info("delete question and options success, id=[{}].", questionId);
			} else {
				bean.setMessage("试题删除失败!");
				bean.setCode(0);
				LOGGER.error("delete question and options error.");
			}
		} catch (Exception e) {
			bean.setCode(0);
			LOGGER.error("delete question and options error, id=[{}], errorMsg=[{}].", questionId,
					e.getMessage());
			bean.setMessage("试题删除失败!");
		}
		return bean;
	}

	/**
	 * 新增试卷
	 * 
	 * @param model
	 *            要更新的题库题目信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/addPaper")
	public JsonBean addPaper(@RequestBody QuestionReqBean model) {
		JsonBean bean = new JsonBean();
		try {
			if (model.getPaperName() == null || "".equals(model.getPaperName())) {
				bean.setCode(0);
				bean.setMessage("参数错误.");
				return bean;
			}
			Paper p = new Paper();
			p.setTitle(model.getPaperName().trim());
			p.setOrgId(UserUtils.getOrgId());
			List<Paper> pList = paperServiceImpl.pagedList(p);
			if (pList.size() >= 1) {
				bean.setCode(0);
				bean.setMessage("该评测试卷名称已经存在.");
				return bean;
			}
			/**
			 * 构建试卷
			 */
			Paper paper = new Paper();
			String paperId = ObjectId.get().toString();
			paper.setId(paperId);
			paper.setTitle(model.getPaperName());
			paper.setCreateTime(new Date());
			paper.setOrgId(UserUtils.getOrgId());
			paper.setCurrent(false);
			paper.setYear(DateFormatUtils.format(new Date(), "yyyy"));
			// 保存试卷
			paperServiceImpl.save(paper);
			/**
			 * 构建试题
			 */
			String[] questionStr = model.getQuestions().split(",");
			Question queTmep = new Question();
			Date nowDate = new Date();
			for (int i = 0; i < questionStr.length; i++) {
				queTmep = questionServiceImpl.get(questionStr[i]);
				String oldQuesId = queTmep.getId();
				String newQuesId = ObjectId.get().toString();
				/**
				 * 构建选项
				 */
				Options options = new Options();
				options.setQuestionId(oldQuesId);
				List<Options> optList = optionsServiceImpl.pagedList(options);
				for (Options opts : optList) {
					opts.setId(ObjectId.get().toString());
					opts.setQuestionId(newQuesId);
					// 保存选项
					optionsServiceImpl.save(opts);
				}
				queTmep.setId(newQuesId);
				queTmep.setPaperId(paperId);
				queTmep.setCreateTime(nowDate);
				queTmep.setTag(false);
				queTmep.setNo(i + 1);
				// 保存试题
				questionServiceImpl.save(queTmep);
				bean.setCode(1);
				bean.setMessage("新增试卷成功.");
			}
		} catch (Exception e) {
			bean.setCode(0);
			bean.setMessage("新增试卷失败!");
			LOGGER.error("do  Add Paper info, errorMsg=[{}].", e.getMessage());
		}
		return bean;
	}

	/**
	 * 获得测评试卷List，Json格式。
	 * 
	 * @param model
	 *            参数
	 * @return 测评试卷
	 */
	@ResponseBody
	@RequestMapping("/paperList")
	public Map<String, Object> paperList(Paper model) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			model.setOrgId(UserUtils.getOrgId());
			model.setOrderBy("create_time desc");
			model.setStart(model.getPage());
			model.setOrderBy(" create_time desc");
			List<Paper> list = paperServiceImpl.pagedList(model);
			// 统计的时候，不需要分页
			model.setStart(null);
			long totalRecord = paperServiceImpl.pagedList(model).size();

			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("paper query success.");
			}
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("get paper list error, errorMsg=[{}].", e.getMessage());
		}
		return result;
	}

	/**
	 * 修改试卷合格线
	 * 
	 * @param model
	 */
	@ResponseBody
	@RequestMapping("/modifyLine")
	public JsonBean modifyLine(@RequestBody QuestionReqBean model) {
		JsonBean bean = new JsonBean();
		if (StringUtils.isBlank(model.getId())) {
			bean.setMessage("参数异常!");
			bean.setCode(0);
			return bean;
		}
		String id = model.getId();
		String qualified = model.getQualified();
		try {
			Paper p = new Paper();
			p.setId(id);
			p.setOrgId(UserUtils.getOrgId());
			p.setQualified(qualified);
			// 修改试卷合格线
			int result = paperServiceImpl.updateById(p);
			if (result == 1) {
				bean.setMessage("修改试卷合格线成功!");
				bean.setCode(1);
				LOGGER.info("update papaer score success, id=[{}].", id);
				// 更新投资人测评是否通过状态
				// 选择需要更新测评状态投资人列表
				List<String> strList = answerServiceImpl.getInvestorList(id);
				for (String string : strList) {
					Investor i = investorServiceImpl.get(string);
					// 如果之前已通过,则判断是更新合格线后导致测评未通过
					if (i.getRiskPass() && i.getScore() < Integer.parseInt(qualified)) {
						i.setRiskPass(false);
						// 如果之前未通过,则判断是更新合格线后导致测评通过
					} else if (!i.getRiskPass() && i.getScore() >= Integer.parseInt(qualified)) {
						i.setRiskPass(true);
					}
					investorServiceImpl.updateById(i);
				}
			} else {
				bean.setMessage("修改试卷合格线失败!");
				bean.setCode(0);
				LOGGER.error("update papaer score error.");
			}
		} catch (Exception e) {
			bean.setCode(0);
			LOGGER.error("update papaer score error, id=[{}], errorMsg=[{}].", id, e.getMessage());
			bean.setMessage("修改试卷合格线失败!");
		}
		return bean;
	}

	/**
	 * 更新试卷启用状态
	 * 
	 * @param model
	 */
	@ResponseBody
	@RequestMapping("/paperState")
	public JsonBean paperState(@RequestBody QuestionReqBean model) {
		JsonBean bean = new JsonBean();
		if (StringUtils.isBlank(model.getId()) || StringUtils.isBlank(model.getCurrent())) {
			bean.setMessage("参数异常!");
			bean.setCode(0);
			return bean;
		}
		String id = model.getId();
		String current = model.getCurrent();
		String orgId = UserUtils.getOrgId();
		try {
			Paper p = new Paper();
			p.setId(id);
			if ("false".equals(current)) {
				// 禁用机构下当前状态为启用状态的试卷
				paperServiceImpl.forbidPpaer(orgId);
				p.setCurrent(true);
			} else if ("true".equals(current)) {
				p.setCurrent(false);
			}
			// 修改试卷启用状态
			int result = paperServiceImpl.updateById(p);
			if (result == 1) {
				bean.setMessage("修改试卷状态成功!");
				bean.setCode(1);
				LOGGER.info("update papaer state  success, id=[{}].", id);
			} else {
				bean.setMessage("修改试卷状态失败!");
				bean.setCode(0);
				LOGGER.error("update papaer  state error.");
			}
		} catch (Exception e) {
			bean.setCode(0);
			LOGGER.error("update papaer state error, id=[{}], errorMsg=[{}].", id, e.getMessage());
			bean.setMessage("修改试卷状态失败!");
		}
		return bean;
	}

	/**
	 * 查看投资人详情页。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 投资人详情页
	 */
	@RequestMapping("/paperDetail/{id}")
	public String detail(@PathVariable("id") String id, Map<String, Object> maps) {
		try {
			if (StringUtils.isBlank(id)) {
				return "common/error";
			}
			Paper p = new Paper();
			p = paperServiceImpl.get(id);
			// 获取试题列表
			Question ques = new Question();
			ques.setPaperId(id);
			ques.setOrderBy("no asc");
			List<Question> quesList = questionServiceImpl.pagedList(ques);
			List<QuestionDetailBean> quesDetailList = new ArrayList<QuestionDetailBean>();
			for (Question question : quesList) {
				QuestionDetailBean tempBean = new QuestionDetailBean();
				tempBean.setQuestion(question);
				Options opt = new Options();
				opt.setQuestionId(question.getId());
				opt.setOrderBy("no asc");
				List<Options> optList = optionsServiceImpl.pagedList(opt);
				for (Options options : optList) {
					tempBean.addOptions(options);
				}
				quesDetailList.add(tempBean);
			}
			maps.put("quesDetailList", quesDetailList);
			maps.put("paperName", p);
		} catch (Exception e) {
			return "common/error";
		}
		return "riskEvaluation/paperDetail";
	}

	/**
	 * 获取测评结果详情
	 * 
	 * @param model
	 * @return 消息List
	 */
	@RequestMapping("/evaluDetail/{id}")
	public String evaluDetail(@PathVariable("id") String id, Map<String, Object> maps) {
		try {
			if (StringUtils.isBlank(id)) {
				return "common/error";
			}
			Map<String, Object> map = questionServiceImpl.getEvulaDetail(id);
			maps.put("quesDetailList", map.get("quesDetailList"));
			maps.put("paperName", map.get("paperName"));
			maps.put("investor", map.get("investor"));
		} catch (Exception e) {
			LOGGER.error("get Investor list error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "riskEvaluation/evaluDetail";
	}

	/**
	 * 用@RequestParam注解来指定表单上的file为MultipartFile
	 * 
	 * @param file
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/downloadFile")
	public JsonBean downloadFile(String filePath, HttpServletResponse response) {
		JsonBean jsonBean = new JsonBean();
		try {
			// 发起请求的参数
			LOGGER.info("request file download, url=[{}]", filePath);
			MyFileUtils.downloadFile(filePath, response);

			// 封装jsonBean
			jsonBean.setCode(1);
			jsonBean.setMessage(SUCCESS);

		} catch (Exception e) {
			LOGGER.error("download file error, error=[{}]", e.getMessage());
			jsonBean.setCode(0);
			jsonBean.setMessage("download file error");
		} finally {
			String path = filePath.substring(0, filePath.lastIndexOf("/"));
			File file = new File(path);
			MyFileUtils.deleteFileDir(file);
		}

		return jsonBean;
	}

	/**
	 * 直接下载试卷结果
	 * 
	 * @param model
	 */
	@ResponseBody
	@RequestMapping("/directDownRes/{id}")
	public String directDownRes(@PathVariable String id, HttpServletResponse response) {
		JsonBean bean = new JsonBean();
		String outputFile = "";
		if (StringUtils.isBlank(id)) {
			LOGGER.info("directDownRes param is error");
			return "common/error";
		}
		try {
			//获取试卷、投资人信息、测评结果信息
			Map<String, Object> map = questionServiceImpl.getEvulaDetail(id);
			Paper p = (Paper) map.get("paperName");
			Investor investor = (Investor) map.get("investor");
			String imagesPrefix = PropsUtils.get("images.prefix");
			String idCard = "-";
			if(!StringUtils.isBlank(investor.getIdcard())){
				idCard = investor.getIdcard();
			}
			@SuppressWarnings("unchecked")
			List<QuestionDetailBean> quesDetailList = (List<QuestionDetailBean>) map.get("quesDetailList");
			// 拼接测评试卷结果html
			String html = "<div id=\"paper_content\" class=\"tab-content\">"
					+ "<div class=\"tab-pane active\">"
					+ "<div class=\"panel-body\">"
					+ "<div class=\"wrapper wrapper-content animated fadeInRight ecommerce\">"
					+ "<div class=\"row\">"
					+ "<div class=\"col-lg-12\">"
					+ "<center>"
					+ "<label class=\"control-label\"  style=\"font-size:18pt;\">试卷名称: "
					+ "投资者尽职调查问卷"
					+ "</label><br/><br/>"
					+ "<label class=\"control-label\"  style=\"margin-left:0px;\">测评人:"
					+ investor.getName()
					+ "</label>"
					+ "<label class=\"control-label\" style=\"margin-left:20px;\">&nbsp;&nbsp;&nbsp;证件号码:"
					+ idCard
					+ "</label>"
					+ "<br/><label class=\"control-label\" style=\"margin-left:20px;\">&nbsp;&nbsp;&nbsp;测评时间: "
					+ DateFormatUtils.format(investor.getEvaluationTime(), "yyyy-MM-dd")
					+ "</label>"
					+ "<label class=\"control-label\" style=\"margin-left:20px;\">&nbsp;&nbsp;&nbsp;得分: "
					+ investor.getScore()
					+ "分</label>"
					+ "&nbsp;&nbsp;&nbsp;";
			if (investor.getRiskPass()) {
				html = html
						+ "<label style=\"font-size:20pt;color:red;margin-left:40px;\">通过</label>";
			} else {
				html = html
						+ "<label style=\"font-size:20pt;color:red;margin-left:40px;\">未通过</label>";
			}
			html = html
					+ "</center><br/><div class=\"ibox float-e-margins\"><div class=\"ibox-content\">";
			for (QuestionDetailBean quesList : quesDetailList) {
				html = html + "<tr><td align = \"center\" ><label style=\"font-size:13pt;\">"
						+ quesList.getQuestion().getNo() + "、</label></td>"
						+ "<td align = \"center\" ><label style=\"font-size:13pt;\">"
						+ quesList.getQuestion().getTitle() + "</label></td></tr><br/>";
				for (Options quesOpts : quesList.getOptList()) {
					html = html
							+ "&nbsp;&nbsp;&nbsp;<tr><td align = \"center\">"
							+ quesOpts.getNo()
							+ ".</td><td align = \"center\">"
							+ quesOpts.getContent()
							+ "</td>"
							+ "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<td align = \"center\" style=\"margin-left:50px;\">"
							+ quesOpts.getScore() + "分</td></tr>";
				}
				html = html + "&nbsp;&nbsp;&nbsp;&nbsp;<td align = \"center\">";
				html = html + "<br/>测评人答案:";
				if (quesList.getQuestion().getAnswer() == null
						|| quesList.getQuestion().getAnswer().equals("")) {
					html = html + "无";
				} else {
					html = html + quesList.getQuestion().getAnswer();
				}
				html = html + "</td><br/><br/>";
			}
			html = html + "<label class=\"control-label\"  style=\"font-size:14pt;\">投资人签名确认:</label><br/>";
			html = html + "<img alt=\"理财师签字\" style=\"width:200px;height:150px;\" src=\""+imagesPrefix+investor.getSignImage()+"\"></img>";
			html = html + "</div></div></div></div></div></div></div></div>";
			outputFile = p.getTitle()+"_"+investor.getName()+"_测评结果.pdf";
			ITextRenderer renderer = new ITextRenderer();
			// 解决中文支持问题
			ITextFontResolver fontResolver = renderer.getFontResolver();
			fontResolver.addFont("C:/Windows/fonts/simsun.ttc", BaseFont.IDENTITY_H,
					BaseFont.NOT_EMBEDDED);
			StringBuffer htmlStr = new StringBuffer();
			// 添加html头文件以免中文加载出错
			htmlStr.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
			htmlStr.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">")
					.append("<head>")
					.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />")
					.append("<style type=\"text/css\" mce_bogus=\"1\">body {font-family: SimSun;}</style>")
					.append("</head>").append("<body>");
			htmlStr.append(html);
			htmlStr.append("</body></html>");
			renderer.setDocumentFromString(htmlStr.toString());
			// 解决图片的相对路径问题
			renderer.getSharedContext().setBaseURL("file:/c:/");
			renderer.layout();
			response.setCharacterEncoding("utf-8");
			response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(outputFile, "UTF-8"));
			response.setContentType("application/octet-stream; charset=utf-8");
			renderer.createPDF(response.getOutputStream());
			bean.setCode(1);
			bean.setMessage("下载试卷结果成功!");
		} catch (Exception e) {
			LOGGER.error("directDownRes error due to [{}]",e.getMessage());
			return "common/error";
		} 
		return "";
	}
}
